const querySQL = require('./common')

let queryBooks = (req, res) => {
  let sql = "select * from books";
  querySQL(sql).then((result)=>{
    res.send({
      status: 200,
      msg: "获取图书成功",
      result,
    });
  })
  .catch((err) => {
    console.log(err);
  });
};

let addBook = (req, res) => {
  let name = req.body.name;
  let author = req.body.author;
  let des = req.body.des;
  let gender = 0;
  if(req.body.gender) gender = req.body.gender;
  let sql = `insert into books (name,author,des,gender) values(?,?,?,?)`
  querySQL(sql,[name,author,des,gender]).then((result)=>{
    if(result.affectedRows == 1) {
      res.send({
        status: 200,
        msg: "添加图书成功",
      });
    } else {
      res.send({
        status: 200,
        msg: "添加图书失败",
      });
    }
  })
  .catch((err) => {
    console.log(err);
  });
};

let delBook = (req, res) => {
  let id = req.params.id;
  let sql = `delete from books where id = ${id}`
  querySQL(sql).then((result)=>{
    if(result.affectedRows == 1) {
      res.send({
        status: 200,
        msg: "删除图书成功",
      });
    } else {
      res.send({
        status: 200,
        msg: "删除图书失败",
      });
    }
    
  })
  .catch((err) => {
    console.log(err);
  });
};


let queryBook = (req, res) => {
  let id = req.params.id;
  let sql = `select * from books where id = ${id}`;
  querySQL(sql).then((result)=>{
      res.send({
        status: 200,
        msg: "查询图书成功",
        result
      });
  })
  .catch((err) => {
    console.log(err);
  });
};


let updateBook = (req, res) => {
  let id = req.body.id;
  let name = req.body.name;
  let author = req.body.author;
  let des = req.body.des;
  let gender = 0;
  if(req.body.gender) gender = req.body.gender;

  let sql = `update   books  set  name=? , author=? , des=?, gender=? where id=?`;
  querySQL(sql,[name,author,des,gender,id]).then((result)=>{
    if(result.affectedRows == 1) {
      res.send({
        status: 200,
        msg: "修改图书成功",
      });
    } else {
      res.send({
        status: 204,
        msg: "修改图书失败",
      });
    }
  })
  .catch((err) => {
    console.log(err);
  });
};

let booksControl = {
  queryBooks,
  addBook,
  delBook,
  queryBook,
  updateBook,
};

module.exports = booksControl;
